// 搜索
const search=document.querySelector('input')
const searchUl=document.querySelector('.searchUl')
const searchUll=document.querySelector('.searchUll')

search.oninput=function(){
    const text=this.value
    const script=document.createElement('script')
    script.src = 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=34099,33970,34004,33855,33607,26350,22159&wd=' + text + '&req=2&csor=5&pwd=aiqiyi&cb=fn&_=1623047595324'
    document.body.appendChild(script)
    script.remove()
}
function fn(res){
    if(!res.g){
        searchUl.style.display='none'
        searchUll.style.display='none'
        return
    }
    let str=''
    res.g.forEach(item=>{
        str+=`<li>${item.q}</li>`

    })
    searchUl.innerHTML=str
    searchUl.style.display='block'
    searchUll.innerHTML=str
    searchUll.style.display='block'
}
// 吸顶
window.addEventListener("scroll",()=>{
    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop; 
    let offsetTop = document.querySelector('.search').offsetTop;
    if (scrollTop > offsetTop) {
         document.querySelector('.search').style.position="fixed";
         document.querySelector('.search').style.top="0px";
         document.querySelector('.search').style.backgroundColor="white";
         document.querySelector('.search').style.zIndex="999";
         
    } else {
         document.querySelector('.search').style.position="";
         document.querySelector('.search').style.top="";
         
}})

// 渲染

const cateBox = document.querySelector('.category > ul')
const listBox = document.querySelector('.list')
const pageBox = document.querySelector('.pageInfo')
const filterbox = document.querySelector('.box')
const sorts = document.querySelectorAll('.sortItem > span')
const select = document.querySelector('select')

getCategoryList()
async function getCategoryList() {
  const res = await pAjax({
    url: 'http://localhost:8888/goods/category',
    dataType: 'json'
  })

  let str = ``

  res.list.forEach(item => {
    str += `<li class="cateItem">${ item }</li>`
  })

  cateBox.innerHTML = str
}

const listInfo = {
  current: 1,
  pagesize: 12,
  search: '',
  filter: '',
  saleType: 0,
  sortType: '',
  sortMethod: '',
  category: ''
}

const filterArr = []


getGoodsList()
async function getGoodsList() {

  let data = ''
  for (let key in listInfo) {
    if (listInfo[key]) data += key + '=' + listInfo[key] + '&'
  }
  data = data.slice(0, -1)
  const res = await pAjax({
    url: 'http://localhost:8888/goods/list',
    data,
    dataType: 'json'
  })
  const { list, total } = res
  let str = ''
  list.forEach(item => {
    str += `
      <li data-id="${ item.goods_id }">
        <div class="show">
          <img src="${ item.img_big_logo }" alt="">
        </div>
        <div class="desc">
          <p class="info">${ item.title }</p>
          <p class="price">
            <span class="current">￥ ${ item.current_price }</span>
            <span class="old">￥ ${ item.price }</span>
          </p>
          <button data-id="${ item.goods_id }">直接购买</button>
        </div>
        <span class="tip ${ item.is_hot ? 'active' : '' }">HOT</span>
        <span class="tip ${ item.is_sale ? 'active' : '' }">SALE</span>
      </li>
    `
  })
  listBox.innerHTML = str
  pageBox.innerHTML = ` ${ listInfo.current } / ${ total } `
}

filterbox.addEventListener('click', e => {
  e = e || window.event
  const target = e.target || e.srcElement
  if (target.className === 'cateItem') {
    console.log('你点击的是分类内容')
    listInfo.category = target.innerText
    getGoodsList()
    for (let i = 0; i < cateBox.children.length; i++) {
      cateBox.children[i].classList.remove('active')
    }
    target.classList.add('active')
  }
  if (target.className.indexOf('filterItem') !== -1) {
    const type = target.dataset.type
    filterArr.push(type)
    listInfo.filter = [ ...new Set(filterArr) ].join(',')
    target.classList.add('active')
    getGoodsList()
  }
  if (target.className === 'searchBtn') {
    const searchText = target.previousElementSibling.value
    listInfo.search = searchText
    getGoodsList()
  }
  if (target.className === 'sortItem') {
    console.log('点击的是排序按钮')
    const type = target.dataset.type
    const method = target.dataset.method
    for (let i = 0; i < sorts.length; i++) {
      sorts[i].classList.remove('active')
    }
    if (method === 'ASC') {
      target.dataset.method = 'DESC'
      target.lastElementChild.classList.add('active')
    } else {
      target.dataset.method = 'ASC'
      target.firstElementChild.classList.add('active')
    }

    listInfo.sortType = type
    listInfo.sortMethod = method === 'ASC' ? 'DESC' : 'ASC'
    getGoodsList()
  }
  if (target.className === 'prev') {
    if (listInfo.current !== 1) listInfo.current--
    getGoodsList()
  }
  if (target.className === 'next') {
    listInfo.current++
    getGoodsList()
  }
})

select.addEventListener('change', () => {
  const pagesize = select.value
  listInfo.pagesize = pagesize
  getGoodsList()
})

listBox.addEventListener('click', async e => {
  e = e || window.event
  const target = e.target || e.srcElement
  if (target.tagName === 'LI') {
    const id = target.dataset.id
    window.sessionStorage.setItem('goods_id', id)
    window.location.href = './details.html'
  }
  if (target.tagName === 'BUTTON') {
    const id = window.localStorage.getItem('id')
    const token = window.localStorage.getItem('token')
    if (!id || !token) {
      const result = window.confirm('您还没有登录, 点击确定跳转到登录页, 点击取消稍后在购买 !')
      window.localStorage.setItem('url', 'list')
      if (result) window.location.href = './login.html'
      return
    }
    const goodsId = target.dataset.id
    const res = await pAjax({
      url: 'http://localhost:8888/cart/add',
      token,
      data: `id=${id}&goodsId=${goodsId}`,
      method: 'post',
      dataType: 'json'
    })
    if (res.code === 1) window.alert('加入购物车成功了')
  }
})

listBox.addEventListener('click', async e => {
  e = e || window.event
  const target = e.target || e.srcElement
  if (target.className === 'data_img') {
    const id = target.dataset.id
    window.sessionStorage.setItem('goods_id', id)
    window.location.href = './details.html'
  }
  if (target.tagName === 'BUTTON') {
    const id = window.localStorage.getItem('id')
    const token = window.localStorage.getItem('token')
    if (!id || !token) {
      const result = window.confirm('您还没有登录, 点击确定跳转到登录页, 点击取消稍后在购买 !')
      window.localStorage.setItem('url', 'list')
      if (result) window.location.href = './login.html'
      return
    }
    const goodsId = target.dataset.id
    console.log(goodsId)
    const res = await pAjax({
      url: 'http://localhost:8888/cart/add',
      token,
      data: `id=${id}&goodsId=${goodsId}`,
      method: 'post',
      dataType: 'json'
    })
    if (res.code === 1) window.alert('加入购物车成功了')
  }
})